import { Toast } from "vant";

export const useDraw = (D, canvas, options) => {
  D.ctx = canvas.getContext("2d");
  D.ctx.lineCap = "round";
  let startX = 0;
  let startY = 0;
  let moveX = 0;
  let moveY = 0;
  canvas.ontouchstart = function (e) {
    e.preventDefault();
    startX = parseInt(e.changedTouches[0].pageX - canvas.offsetLeft);
    startY = parseInt(
      e.changedTouches[0].pageY -
        canvas.offsetTop +
        document.getElementById("main").scrollTop
    );
    D.ctx.strokeStyle = options.color;
    D.ctx.moveTo(startX, startY);
    D.position.push({ startX, startY });
    return false;
  };
  canvas.ontouchmove = function (e) {
    moveX = parseInt(e.changedTouches[0].pageX - canvas.offsetLeft);
    moveY = parseInt(
      e.changedTouches[0].pageY -
        canvas.offsetTop +
        document.getElementById("main").scrollTop
    );
    D.ctx.lineWidth = 10;
    D.ctx.lineTo(moveX, moveY);
    D.ctx.stroke();
    D.position.push([moveX, moveY]);
    return false;
  };
};

export const useClearDraw = (D, canvas) => {
  D.ctx.clearRect(0, 0, canvas.width, canvas.height);
  D.ctx.beginPath();
};

export const useBackLastDraw = (D) => {
  const canvas = D.canvas;
  const ctx = D.ctx;
  if (D.position.length <= 0) {
    return Toast("您还没绘制过或您已经回退过一次了，再次绘制一次吧！");
  }
  useClearDraw(D, canvas);
  let animation;
  let index = 0;
  function animation_method() {
    if (index >= D.position.length) {
      D.position = [];
      return window.cancelAnimationFrame(animation);
    }
    if (
      Object.prototype.toString.call(D.position[index]) === "[object Object]"
    ) {
      ctx.moveTo(D.position[index].startX, D.position[index].startY);
    } else {
      ctx.lineTo(D.position[index][0], D.position[index][1]);
    }
    ctx.stroke();
    animation = window.requestAnimationFrame(animation_method);
    index++;
  }
  animation = window.requestAnimationFrame(animation_method);
};
